<template>
  <div class="form-container">
    <el-row :gutter="15">
      <el-col
        :xs="24"
        :sm="24"
        :md="12"
        :lg="8"
        :xl="8"
      >
        <el-form
          ref="ruleForm"
          :model="ruleForm"
          :rules="rules"
          label-width="100px"
          class="demo-ruleForm"
          :status-icon="true"
        >
          <el-form-item
            v-if="user.level < 3"
            label="所属村"
            prop="villageWrap"
          >
            <el-cascader
              v-model="ruleForm.villageWrap"
              :options="villageCascader"
              :props="villageProp"
              placeholder="请选择所属村"
              clearable
              @change="change"
            />
          </el-form-item>
          <el-form-item
            label="补助类型"
            prop="type"
          >
            <el-select
              v-model.number="ruleForm.type"
              placeholder="请选择补助类型"
              clearable
            >
              <el-option
                v-for="item in typeAtt"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
          <el-form-item
            label="补助项名称"
            prop="name"
          >
            <el-input
              v-model="ruleForm.name"
              placeholder="请输入补助项名称"
              clearable
            />
          </el-form-item>
          <el-form-item
            label="补助物品"
            prop="items"
          >
            <el-input
              v-model="ruleForm.items"
              placeholder="请输入补助物品"
              clearable
            />
          </el-form-item>
          <el-form-item
            label="补助金额"
            prop="amount"
          >
            <el-input
              v-model.number="ruleForm.amount"
              placeholder="请输入补助金额"
              clearable
            />
          </el-form-item>
          <el-form-item
            label="补助标准"
            prop="standards"
          >
            <el-input
              v-model="ruleForm.standards"
              placeholder="请输入补助标准"
              clearable
            />
          </el-form-item>
          <el-form-item
            label="申请时间"
            prop="applicationTime"
          >
            <el-date-picker
              v-model="ruleForm.applicationTime"
              align="right"
              type="date"
              placeholder="请选择申请时间"
              value-format="yyyy-MM-dd"
              :picker-options="pickerOptions1"
              clearable
            />
          </el-form-item>
          <el-form-item
            label="领取时间"
            prop="pickUpTime"
          >
            <el-date-picker
              v-model="ruleForm.pickUpTime"
              align="right"
              type="date"
              placeholder="请选择领取时间"
              value-format="yyyy-MM-dd"
              :picker-options="pickerOptions1"
              clearable
            />
          </el-form-item>
          <el-form-item
            label="国家政策"
            prop="nationalPolicy"
          >
            <el-input
              v-model="ruleForm.nationalPolicy"
              type="textarea"
              placeholder="请输入相关国家政策"
            />
          </el-form-item>
          <el-form-item
            label="实施政策"
            prop="implementationPolicy"
          >
            <el-input
              v-model="ruleForm.implementationPolicy"
              type="textarea"
              placeholder="请输入相关实施政策"
            />
          </el-form-item>

          <el-form-item>
            <el-button
              type="primary"
              @click="submitForm('ruleForm')"
            >
              {{ !id ? "立即创建" : "保存编辑" }}
            </el-button>
            <el-button @click="resetForm('ruleForm')">
              重置
            </el-button>
          </el-form-item>
        </el-form>
      </el-col>
    </el-row>
  </div>
</template>

<script>
//手动添加
import { mapGetters } from "vuex";
export default {
  name: "Form",
  props: {
    id: {},
  },
  data() {
    return {
      ruleForm: {
        region: "",
        delivery: false,
        // type: [],
        resource: "",
        desc: "",

        village: [],
        villager: "",
        type: "",
        name: "",
        items: "",
        // amount: "",
        standards: "",
        // applicationTime: "",
        // pickUpTime: "",
        nationalPolicy: "",
        implementationPolicy: "",
      },
      rules: {
        name: [
          { required: true, message: "请输入补助项名称", trigger: "blur" }
        ],
        villageWrap: [
          { required: true, message: "请选择所属村", trigger: "change" },
        ],
        type: [
          {
            required: true,
            message: "请选择补助类型",
            trigger: "change",
          },
        ],
        items: [
          { required: false, message: "请输入补助物品", trigger: "blur" },
        ],
        amount: [{ required: false, message: "请输入补助金额", trigger: "blur" }],
        standards: [{ required: false, message: "请输入补助标准", trigger: "blur" }],
        applicationTime: [{ required: false, message: "请选择申请时间", trigger: "change" }],
        pickUpTime: [{ required: false, message: "请选择领取时间", trigger: "change" }],
        nationalPolicy: [{ required: false, message: "请输入国家政策", trigger: "blur" }],
        implementationPolicy: [{ required: false, message: "请输入实施政策", trigger: "blur" }],
      },
      dialogVisible: false,
      villagerAtt: [],
      createForm: {},
      villageCascader: [],
      villageProp: {
        value: "id",
        label: "name",
      },
      pickerOptions1: {
        disabledDate(time) {
          return false
        },
        shortcuts: [
          {
            text: "今天",
            onClick(picker) {
              picker.$emit("pick", new Date());
            },
          },
          {
            text: "昨天",
            onClick(picker) {
              const date = new Date();
              date.setTime(date.getTime() - 3600 * 1000 * 24);
              picker.$emit("pick", date);
            },
          },
          {
            text: "一周前",
            onClick(picker) {
              const date = new Date();
              date.setTime(date.getTime() - 3600 * 1000 * 24 * 7);
              picker.$emit("pick", date);
            },
          },
        ],
      },
      typeAtt: [],
    };
  },
  computed: {
    ...mapGetters({
      user: "user/info",
    }),
  },
  async created() {
    this.init();
    this.id && this.fetchData(this.id);
  },
  methods: {
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid && this.id) {
          // alert("submit!");
          this.edit()
        } else if(valid && !this.id) {
          // return false;
          this.create();
        } else {
          return false
        }
      });
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
    resPip() {
      this.createForm = JSON.parse(JSON.stringify(this.ruleForm));
    },
    async create() {
      this.resPip();
      const res = await this.$http.post(`/subsidy`, this.createForm);
      if (res.status == 201) {
        this.$baseMessage("新增成功", "success");
        this.$router.push({ name: "Subsidy" });
      } else {
        this.$baseMessage("新增失败", "error");
      }
    },
    async edit() {
      this.resPip();
      const res = await this.$http.put(`/subsidy/${this.id}`, this.createForm);
      if (res.status == 200) {
        this.$baseMessage("修改成功", "success");
        this.$router.push({ name: "Subsidy" });
      } else {
        this.$baseMessage("修改失败", "error");
      }
    },
    async fetchData(id) {
      const res = await this.$http.get(`subsidy/${id}?join=village&join=type`);
      
      //处理关联
      // res.data.villager = res.data.villager.id;
      
      const town = await this.$http.get(`village/${res.data.village.id}?join=town`);

      this.villagerAtt = town.data.villager;
      const area = await this.$http.get(`town/${town.data.town.id}?join=area`);
      res.data.villageWrap = [
        area.data.area.id,
        town.data.town.id,
        res.data.village.id,
      ];

      //手动触发
      this.change([
        area.data.area.id,
        town.data.town.id,
        res.data.village.id,
      ])
      //处理关联
      res.data.village = res.data.village.id;

      res.data.type = res.data.type.id;

      this.ruleForm = Object.assign({}, res.data);

      console.log(this.ruleForm);

      // this.town =
      console.log(this.ruleForm, res.data);
    },
    async init() {
      const res = await this.$http.get(`area?join=town&join=town.village`);
      res.data.forEach(area => {
        area.children = area.town
        area.town.forEach(town => {
          town.children = town.village
        })
      })
      this.villageCascader = res.data;
      this.setSelectItem()
    },
    async change(val) {
      this.ruleForm.village = val[val.length - 1];
      this.ruleForm.type = "";
      const res = await this.$http.get(`village/${this.ruleForm.village}?join=subsidyType`);
      this.typeAtt = res.data.subsidyType;
    },
    setSelectItem() {
      if(this.user.level < 1) {
      } else if (this.user.level == 1) {
        //区级
        this.villageCascader.forEach((area) => {
          if(area.id == this.user.area.id) {
            area.disabled = false
          } else {
            area.disabled = true
            if (area.town.length > 0) {
              area.town.forEach((town) => {
                town.disabled = true
              });
            }
          }
        });
      } else if (this.user.level == 2) {
        //镇级
        this.villageCascader.forEach((area) => {
          if(area.id == this.user.area.id) {
            area.disabled = false
             if (area.town.length > 0) {
              area.town.forEach((town) => {
                if(town.id == this.user.town.id) {
                  town.disabled = false
                } else {
                  town.disabled = true
                }
              });
            }
          } else {
            area.disabled = true
            if (area.town.length > 0) {
              area.town.forEach((town) => {
                  town.disabled = true
              });
            }
          }
        });
      } 
        else if (this.user.level == 3) {
          //村级
        this.ruleForm.village = this.user.village.id
        this.change([this.ruleForm.village])
      } 
    },
  },
};
</script>
